package net.fltx.p2p.common;

import com.alibaba.fastjson.JSON;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.UUID;

/**
 * 基本报文
 * @author fltx.net
 * @Date 2021/2/22 23:06
 * @Version 1.0
 */
public class Packet<T> {

    protected String username;
    protected String uuid;
    protected Date timestamp=new Date();
    protected PacketType type;
    protected String message;
    protected T data;

    public Packet(){
//        uuid= UUID.randomUUID().toString();
//        timestamp=new Date();
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getUuid() {
        return uuid;
    }

    public void setUuid(String uuid) {
        this.uuid = uuid;
    }

    public Date getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(Date timestamp) {
        this.timestamp = timestamp;
    }

    public PacketType getType() {
        return type;
    }

    public void setType(PacketType type) {
        this.type = type;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }


    public void sendTo(SocketChannel channel){
        String json= JSON.toJSONString(this);
        ByteBuffer buffer=ByteBuffer.wrap(json.getBytes(StandardCharsets.UTF_8));
        try {
            //buffer.flip();
            int write = channel.write(buffer);
            System.out.println("write长度: "+write);
        } catch (IOException exception) {
            exception.printStackTrace();
            throw new RuntimeException("发送失败",exception);
        }

    }


    @Override
    public String toString() {
        return "Packet{" +
                "username='" + username + '\'' +
                ", uuid='" + uuid + '\'' +
                ", timestamp=" + timestamp +
                ", type='" + type + '\'' +
                ", message='" + message + '\'' +
                ", data=" + data +
                '}';
    }
}
